<template>
  <div class="body">
    <div class="login-container">
      <el-form :model="form" status-icon :rules="rules" ref="form" label-width="auto" class="login-form">
        <h1 class="title-zc">后台登录</h1>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" placeholder="请输入用户名"></el-input>
        </el-form-item>

        <el-form-item label="密码" prop="password" style="text-align: left;">
          <el-input type="password" placeholder="请输入密码" v-model="form.password" autocomplete="off" show-password></el-input>
        </el-form-item>
        <el-form-item label="验证码">
          <el-input type="password2" style="width: 150px ;" placeholder="请输入验证码" v-model="form.password2"></el-input>
          <canvas id="canvas1" width="100" height="40"></canvas>
        </el-form-item>
        <div>
          <el-button type="primary" @click="submitForm()"
            style="background-color: black;border: 1px solid #000;border-radius: 3px;margin-top: 10px;">登&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;录</el-button>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script>
export default {
  name: "LoginIndex",
  data() {
    var validateNamePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入用户名"));
      } else if (!/^[a-zA-Z0-9_-]{4,16}$/.test(value)) {
        callback(new Error("4到16位（字母，数字，下划线，减号）"));
      } else {
        callback();
      }
    };
    var validatePwdPass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else if (!/^[a-zA-Z0-9_-]{4,16}$/.test(value)) {
        callback(new Error("4到16位（字母，数字，下划线，减号）"));
      } else {
        callback();
      }
    };

    return {
      form: {
        username: "",
        password: "",
        message: ''
      },
      rules: {
        username: [{ validator: validateNamePass, required: true, trigger: "blur" },
        ],
        password: [{ validator: validatePwdPass, required: true, trigger: "blur" },
        ],
      },
    };
  },
  methods: {
    submitForm() {
      this.$refs.form.validate((valid) => {
        console.log(this.form.username)
        console.log(this.form.password)
        let params = new FormData()
        params.append("userName", this.form.username)
        params.append("password", this.form.password)
        // var params2 ={
        //   "userName": this.form.username,
        //   "password": this.form.password
        // }
        // var a = JSON.stringify(params2)
        // let form=this.form

        if (valid) {
          // var header="?username="+this.form.username+"&password="+this.form.password;
          this.$axios.post('/user/login', params, { timeout: 5000 })
            .then(
              (resp) => {
                if (resp.data.code === 200) {
                  localStorage.clear();
                  var userInfo = resp.data.data;
                  var id = Object.keys(userInfo)[0]
                  this.$store.commit('$_setToken', userInfo[id]);
                  this.$message.success("登录成功！");
                  console.log("userInfo===")
                  // console.log(id)
                  // console.log(userInfo[id])
                  localStorage.setItem('authorId', id);
                  console.log(localStorage.getItem('authorId'))
                  localStorage.setItem('ms_username', this.form.username);
                  localStorage.setItem('tokenStartTime', new Date().getTime())
                  localStorage.setItem('power', resp.data.message)
                  this.$router.push('/admin')
                } else if (resp.data.code === 400) {
                  this.$message.error(resp.data.message);
                } else if (resp.data.code === 500) {
                  this.$message.error(resp.data.message);
                } else {
                  this.$message.error("请检查服务器");
                }
              }
            ).catch(_ => {
              this.errMessage = (_ && _.data && Object.prototype.toString.call(_.data) === '[object Array]') ? _.data[0][Object.keys(_.data[0])[0]] : _.message
              this.$message.error("响应超时，请联系管理员检查服务器")
            })
        } else {
          this.$message.error('请输入账号和密码');
          console.log('error submit!!');
          return false;
        }
      })
    },
  },
  mounted() {
    function randomCode(canvasId, letterLength) {
      //1. 获取画布
      var canvas = document.getElementById(canvasId);
      //2. 获取画笔
      var ctx = canvas.getContext('2d');
      //文本
      var text = randomLetter(letterLength);
      // ctx.fillStyle = randomColor();
      ctx.fillStyle = '#ddd';
      //填充背景色
      ctx.fillRect(0, 0, canvas.width, canvas.height);
      ctx.textBaseline = "top";
      //随机效果：每个字符都是随机的位置和随机的旋转角度
      for (var i = 0; i < text.length; i++) {
        var char = text.charAt(i);//获取对应下标的字符
        ctx.fillStyle = randomColor();
        ctx.font = "16px 微软雅黑";
        ctx.save();//保存画笔的状态
        var randomAngle = Math.random() * 20 - 10;//随机-10 ~ 10度
        ctx.rotate(Math.PI / 180 * randomAngle);
        //位置：高度有个-5~15的范围
        ctx.fillText(char, i * 15, Math.random() * 20 - 5);
        ctx.restore();
      }

      //随机字母或数字
      function randomLetter(num) {
        var arr = "QWERTYUIOASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm1234567890".split("");
        var str = "";
        for (var i = 0; i < num; i++) {
          var index = parseInt(Math.random() * arr.length);
          str += arr[index];
        }

        return str;
      }

      //随机rgb颜色
      function randomColor() {
        var red = parseInt(Math.random() * 256);
        var green = parseInt(Math.random() * 256);
        var blue = parseInt(Math.random() * 256);
        return `rgb(${red},${green},${blue})`;
      }

      return text;
    }
    var text =  randomCode("canvas1",5);
    console.log(text);

    document.getElementById('canvas1').onclick =function(){
      text =  randomCode ("canvas1",5);
      console.log(text);
    }
  }
};
</script>

<style scoped>
.body {
  position: absolute;
  top: 0;
  left: 0;
  overflow-y: hidden;
}

.login-container {
  height: 745px;
  width: 1536px;
  /* background-color: #ffffff; */
  background: url(../assets/img/LoginBackGround.png) no-repeat -200px -160px;
}

.login-form {
  position: absolute;
  right: 200px;
  top: 150px;
  width: 340px;
  height: 360px;
  /* margin: 150px auto; */
  background-color: #ffffff;
  padding: 30px;
  border-radius: 0;
}



.title-zc {
  text-align: center;
  margin-bottom: 40px;
}
</style>
